import React from 'react';
import {injectIntl} from './intl';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {
    PAGE,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH
} from '../constants';
import {Link} from 'react-router-dom';
import {hasPermissions, conventSorter} from './utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import SocSelectPanel from './SocSelectPanel';
export class TablePanel extends React.PureComponent {
    state = {
        data: {},
        socSelectPanelShow: false
    }
    handleClose = id => {
        this.setState({
            loading: true
        });
        const data = this.props.data.find(v => v.id === id);
        this.props.onClickClose({
            dealerId: data.dealerId,
            brandId: data.brandId,
            partId: data.partId,
            productCategoryId: data.productCategoryId,
            lv1FaultItemCode: data.lv1FaultItemCode,
            lv2FaultItemCode: data.lv2FaultItemCode,
            lv3FaultItemCode: data.lv3FaultItemCode,
        }).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    onSocSelect = r => {
        const {data} = this.state;
        const condition = {
            socId: r.id,
            dealerId: data.dealerId,
            brandId: data.brandId,
            partId: data.partId,
            productCategoryId: data.productCategoryId,
            lv1FaultItemCode: data.lv1FaultItemCode,
            lv2FaultItemCode: data.lv2FaultItemCode,
            lv3FaultItemCode: data.lv3FaultItemCode
        };
        this.props.onSubmit(condition).then(success => {
            if(success)
                this.setState({
                    socSelectPanelShow: false
                });
        });
    }
    onSocCancel = () => {
        this.setState({
            data: {},
            socSelectPanelShow: false
        });
    }
    onClickJoin = e => {
        const {id} = e.target.dataset;
        const data = this.props.data.find(v => v.id === id);
        this.setState({
            data,
            socSelectPanelShow: true
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };
    render() {
        const columns = [
            {

                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                sorter: true,
                dataIndex: 'brandCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partCode',
                    defaultMessage: '零件号'
                }),
                dataIndex: 'partCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partName',
                    defaultMessage: '零件名称'
                }),
                dataIndex: 'partName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.lv1FaultItemCode',
                    defaultMessage: '故障代码一级'
                }),
                dataIndex: 'lv1FaultItemCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.lv2FaultItemCode',
                    defaultMessage: '故障代码二级'
                }),
                dataIndex: 'lv2FaultItemCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.lv3FaultItemCode',
                    defaultMessage: ' 故障代码三级'
                }),
                dataIndex: 'lv3FaultItemCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.quantity',
                    defaultMessage: '单据数量'
                }),
                dataIndex: 'quantity'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.project,
                            children: (
                                <Link key="project" to={{
                                    pathname: routes.project.url(),
                                    query: {
                                        dealerId: r.dealerId,
                                        brandId: r.brandId,
                                        partId: r.partId,
                                        productCategoryId: r.productCategoryId,
                                        lv1FaultItemCode: r.lv1FaultItemCode,
                                        lv2FaultItemCode: r.lv2FaultItemCode,
                                        lv3FaultItemCode: r.lv3FaultItemCode,
                                    }
                                }}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.project',
                                        defaultMessage: '立项'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.project) && hasPermissions(r.options, PERMISSION.project))
                        },
                        {
                            id: PERMISSION.join,
                            children: (
                                <a key="join" data-id={r.id} onClick={this.onClickJoin}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.join',
                                        defaultMessage: '加入项目'
                                    })}
                                </a>),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.join) && hasPermissions(r.options, PERMISSION.join))
                        },
                        {
                            id: PERMISSION.close,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="close"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleClose}>
                                    <a key="close">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.close',
                                            defaultMessage: '关闭'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.close) && hasPermissions(r.options, PERMISSION.close))
                        }, {
                            id: 'detail',
                            children: (
                                <Link key="detail" to={{
                                    pathname: routes.detail.url(),
                                    query: {
                                        dealerId: r.dealerId,
                                        brandId: r.brandId,
                                        partId: r.partId,
                                        productCategoryId: r.productCategoryId,
                                        lv1FaultItemCode: r.lv1FaultItemCode,
                                        lv2FaultItemCode: r.lv2FaultItemCode,
                                        lv3FaultItemCode: r.lv3FaultItemCode,
                                    }
                                }}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.detail',
                                        defaultMessage: '详情'
                                    })}
                                </Link>
                            ),
                            hidden: false
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
                {
                    this.state.socSelectPanelShow &&
                    <SocSelectPanel
                        brandCode={this.state.data.brandCode}
                        brandId={this.state.data.brandId}
                        dealerCode={this.state.data.dealerCode}
                        dealerId={this.state.data.dealerId}
                        lv1FaultItemCode={this.state.data.lv1FaultItemCode}
                        lv2FaultItemCode={this.state.data.lv2FaultItemCode}
                        lv3FaultItemCode={this.state.data.lv3FaultItemCode}
                        partCode={this.state.data.partCode}
                        productCategoryCode={this.state.data.productCategoryCode}
                        onCancel={this.onSocCancel}
                        onSelect={this.onSocSelect}/>
                }
            </div>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickClose: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
    onClickClose,
    onClickJoin
} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickClose: data =>
        dispatch(onClickClose(data)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onSubmit: condition =>
        dispatch(onClickJoin(condition)).then(res => {
            if(res.ok)
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
            return res.ok;
        }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
